//
//  AliMNSHttpBodyEncoder.m
//  AlibabaCloudMNSiOS
//
//  Created by David Chen on 28/03/2017.
//  Copyright © 2017 AliCloud. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AliMNSHttpBodyEncoder.h"
#import "AliMNSCommon.h"

@implementation AliMNSHttpBodyEncoder

+(void)addNodeIfValid:(NSString*)nodeName
        withNodeValue:(NSString*)nodeValue
     withInvalidValue:(NSString*)invalidValue
         withDataDict:(NSMutableDictionary*)dataDict
{
    if(![nodeValue isEqualToString:invalidValue])
    {
        [dataDict setValue:nodeValue forKey:nodeName];
    }
}

+(NSString*) encodeDict:(NSString* )nodeName
           withDataDict:(NSMutableDictionary*) dataDict
{
    NSMutableString* xmlStr = [NSMutableString new];
    NSArray* keys = [dataDict allKeys];
    NSUInteger count = [keys count];
    for(int i = 0; i < count; i++)
    {
        id key = [keys objectAtIndex:i];
        id value = [dataDict objectForKey:key];
        [xmlStr appendFormat:@"<%@>%@</%@>", key, value, key];
    }

    return [NSString stringWithFormat:@"%@<%@ xmlns=\"%@\">%@</%@>",
                     [AliMNSCommon getInstance].XML_VERSION_STR, nodeName,
                        [AliMNSCommon getInstance].XMLNS, xmlStr, nodeName];
}

+(NSString*) encodeList:(NSString*) rootNodeName
        withSedNodeName:(NSString*) secNodeName
           withDataList:(NSArray*) dataList
{
    NSMutableString* xmlStr = [NSMutableString new];
    NSUInteger count = [dataList count];
    for(int i = 0; i < count; i++)
    {
        id obj = [dataList objectAtIndex:i];

        if ([obj isKindOfClass:[NSDictionary class]])
        {   // array of dictionary.
            NSDictionary* dict = obj;
            NSMutableString* nodeXmlStr = [NSMutableString new];
            NSArray* keys = [dict allKeys];
            for (int j = 0; j < [keys count]; j++)
            {
                id key = [keys objectAtIndex:j];
                id value = [dict objectForKey:key];
                [nodeXmlStr appendFormat:@"<%@>%@</%@>", key, value, key];
            }
            [xmlStr appendFormat: @"<%@>%@</%@>", secNodeName, nodeXmlStr, secNodeName];
        }
        else
        {   // array of string.
            NSString* strValue = obj;
            [xmlStr appendFormat: @"<%@>%@</%@>", secNodeName, strValue, secNodeName];
        }
    }

    return [NSString stringWithFormat:@"%@<%@ xmlns=\"%@\">%@</%@>",
            [AliMNSCommon getInstance].XML_VERSION_STR, rootNodeName,
            [AliMNSCommon getInstance].XMLNS, xmlStr, rootNodeName];;
}

@end
